package com.guo.loadinganim;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.SharedElementCallback;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.transition.Transition;
import androidx.transition.TransitionValues;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroupOverlay;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.guo.loadinganim.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ImageView mAlbumImageView;
    private LinearLayout mLayout;
    private String picture = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202003%2F18%2F20200318105813_pmbos.thumb.400_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635737969&t=70e439fdfb8a5bd6fab1dba8dfe307b7";
    private String picture1 = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fww2.sinaimg.cn%2Fmw690%2F4ca1100dly1h5kfikvdmoj23uw5cb4qv.jpg&refer=http%3A%2F%2Fwww.sina.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666061058&t=5974e7b7702648b0898f62a4154b6767";
    private static final String TAG = "MainActivity";
    ActivityMainBinding mMainBinding;
    boolean currentIsSmall = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        overridePendingTransition(R.anim.anim_activity_enter, R.anim.anim_activity_exit);
        super.onCreate(savedInstanceState);
        mMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
//        List<String> list = new ArrayList<>();
//        list.add("春");
//        list.add("夏");
//        list.add("秋");
//        list.add("冬");
//        mMainBinding.customRadioGroup.setTextList(list);
//        mMainBinding.customRadioGroup.setRadioButtonChecked(0);
        //setContentView(R.layout.activity_main);
        requestPermission(STORAGE);
    }

    private void initView(){
//        mLayout = findViewById(R.id.layout_parent);
//        mAlbumImageView = findViewById(R.id.image_view);
//        getWindow().getDecorView().setBackground(mLayout.getBackground());
//        //mLayout.setVisibility(View.GONE);
//        Log.d(TAG, "set layout parent gone");
//        Glide.with(this).load(picture).into(mAlbumImageView);
//        Log.d(TAG, "load picture url");
//        if(!Settings.canDrawOverlays(this)){
//            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//            intent.setData(Uri.parse("package:" + getPackageName()));
//            startActivityForResult(intent, 1);
//        }



        //setWindowAnimation();
//
//        FrameLayout linearLayout = findViewById(R.id.card);
//        LayoutAnimManager animManager = new LayoutAnimManager();
//        animManager.initialize(linearLayout);
//
//        linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//                animManager.changeView(currentIsSmall, linearLayout);
//                currentIsSmall = !currentIsSmall;
//                return false;
//            }
//        });
    }

    /**
     * 申请存储权限和摄像头权限
     */
    final String[] STORAGE = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    private void requestPermission(String[] permissions){
        List<String> permissionTBD = new ArrayList<>();
        for(String permission:permissions){
            if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
                permissionTBD.add(permission);
            }
        }
        if(permissionTBD.size() > 0){
            String[] permissionsRequest = new String[permissionTBD.size()];
            for(String permission:permissionTBD){
                permissionsRequest[permissionTBD.indexOf(permission)] = permission;
            }
            requestPermissions(permissionsRequest, 0x123);
            Log.d(TAG, "request permission");
        }else{
//            initView();
            Log.d(TAG, "capture fragment init camera");
        }
    }

    /**
     * 权限申请结果回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 0x123:
                if(null != grantResults && grantResults.length > 0){
                    boolean granted = true;
                    for(Integer integer:grantResults){
                        granted &=(integer == PackageManager.PERMISSION_GRANTED);
                    }
                    if(granted){
                        initView();
                    }else{
                        Toast.makeText(MainActivity.this, "缺失了存储所需权限", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            if(Settings.canDrawOverlays(this)){
                Log.d(TAG, "has permit alert window");
//                initTopBarView();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");

    }

    @Override
    protected void onStop() {
//        exitAnimation();
        super.onStop();
        overridePendingTransition(R.anim.anim_activity_enter, R.anim.anim_activity_exit);
    }


    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        Log.d(TAG, "onActivityReenter");

    }
    private int width, height;
    private int[] latestLoc = new int[2];
    public void enterAnimation(){
        Log.d(TAG, "execute animation");
        if(null == getIntent()){
            Log.d(TAG, "intent is null");
            return;
        }
        Bundle b = getIntent().getExtras();
        if(null == b){
            Log.d(TAG, "bundle is null");
            return;
        }
        mLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                mLayout.getViewTreeObserver().removeOnPreDrawListener(this);
                //mLayout.setVisibility(View.INVISIBLE);
                int[] originLoc = b.getIntArray("loc");
                int originWidth = b.getInt("width");
                int originHeight = b.getInt("height");
                mAlbumImageView.getLocationOnScreen(latestLoc);
                Log.d(TAG, "get album location on screen x = " + latestLoc[0] +", y = "+ latestLoc[1]);
                mAlbumImageView.setPivotX(0.5f);
                mAlbumImageView.setPivotY(0.5f);
                mAlbumImageView.setScaleX(originWidth*1.0f/mAlbumImageView.getWidth());
                mAlbumImageView.setScaleY(originHeight*1.0f/mAlbumImageView.getHeight());
                mAlbumImageView.setTranslationX(originLoc[0] - latestLoc[0]);
                mAlbumImageView.setTranslationY(originLoc[1] - latestLoc[1]);
                width = mAlbumImageView.getWidth();
                height = mAlbumImageView.getHeight();
                mAlbumImageView.animate().scaleX(1).scaleY(1).translationX(0).translationY(0).setDuration(500).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        Log.d(TAG, "animation start");
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        Log.d(TAG, "animation end");
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {

                    }
                });

                return false;
            }
        });
    }

    /**
     * 需要将视图的宽度/高度/位置传递给View
     */
    private void exitAnimation(){
        if(width <= 0 && height <= 0){
            width = mAlbumImageView.getWidth();
            height = mAlbumImageView.getHeight();
            mAlbumImageView.getLocationOnScreen(latestLoc);
        }
        if(width >0 && height > 0){
            Bundle bundle = new Bundle();
            Log.d(TAG, "latest loc x = "+ latestLoc[0] + ", y = " +latestLoc[1]);
            bundle.putIntArray("loc", latestLoc);
            bundle.putInt("width", width);
            bundle.putInt("height", height);
            AnimApplication.getInstance().setExitAnimationBundle(bundle);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onstart");
        enterAnimation();
    }


    @Override
    public void overridePendingTransition(int enterAnim, int exitAnim) {
        super.overridePendingTransition(enterAnim, exitAnim);
        Log.d(TAG, "override pending");
    }

    @Override
    public void setEnterSharedElementCallback(@Nullable SharedElementCallback callback) {
        super.setEnterSharedElementCallback(callback);
        Log.d(TAG, "set enter shared");
    }

    @Override
    public void onEnterAnimationComplete() {
        super.onEnterAnimationComplete();
        Log.d(TAG, "on Enter animation complete");
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_activity_enter, R.anim.anim_activity_exit);
    }

    private void setWindowAnimation(){
       getWindow().setEnterTransition(new ActivityTransition());
        getWindow().setSharedElementEnterTransition(new ActivityTransition());
        getWindow().getDecorView().getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this);
                supportPostponeEnterTransition();
                return false;
            }
        });
    }

}